package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.*;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping(path = "/report")
public class ReportController {

    @Reference
    private MemberService memberService;

    @Reference
    private SetmealService setmealService;

    @Reference
    private ReportService reportService;

    @Reference
    private OrderService orderService;

    /**
     * 会员数量统计 , 统计前12个月 , 每个月的会员数量变化
     *
     * @return
     */
    @RequestMapping("/member/count")
    public Result getMemberReport() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -12);//获得当前日期之前12个月的日期

        List<String> list = new ArrayList<String>();
        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH, 1);
            list.add(new SimpleDateFormat("yyyy-MM").format(calendar.getTime()));
        }

        Map<String, Object> map = new HashMap<>();
        map.put("months", list);

        List<Integer> memberCount = memberService.findMemberCountByMonth(list);
        map.put("memberCount", memberCount);

        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
    }

    /**
     * 套餐预约占比
     *
     * @return
     */
    @RequestMapping("/setmeals")
    public Result getSetmealReport() {
        List<Map<String, Object>> list = setmealService.findSetmealOrderedCount();

        Map<String, Object> map = new HashMap<>();
        map.put("setmealCount", list);

        List<String> setmealNames = new ArrayList<>();
        for (Map<String, Object> m : list) {
            String name = (String) m.get("name");
            setmealNames.add(name);
        }
        map.put("setmealNames", setmealNames);

        return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, map);
    }

    /**
     * 获取运营统计数据
     *
     * @return
     */
    @RequestMapping("/business")
    public Result getBusinessReportData() {
        try {
            Map<String, Object> result = reportService.getBusinessData();
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, result);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    /**
     * 导出运营统计数据
     *
     * @return
     */
    @RequestMapping("/export/business")
    public Result exportBusinessData(HttpServletRequest request, HttpServletResponse response) {
        try {

            String temlateRealPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "food.xlsx";

            //读取模板文件创建Excel表格对象
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(temlateRealPath)));
            XSSFSheet sheet = workbook.getSheetAt(0);

            ServletOutputStream out = response.getOutputStream();
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");
            workbook.write(out);

            out.flush();
            out.close();
            workbook.close();

            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, null);

        } catch (Exception e) {
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL, null);
        }
    }


    /**
     * 预约和到诊
     *
     * @param value
     * @return
     */
    @PostMapping("/order")
    public Result getOrderAndStatus(String value) {
        try {
            Map map = new HashMap();
            List date = null; // date
            List<String> visitsCountList = null;
            List<String> orderCountList = null;
            Calendar calendar = null;
            if (value == null || value == "") {
                calendar = Calendar.getInstance();
                calendar.setTime(new Date());
                calendar.add(Calendar.DATE, -7);
                date = new ArrayList();
                for (int i = 0; i < 7; i++) {
                    calendar.add(Calendar.DATE, 1);
                    date.add(new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()));
                }
                orderCountList = orderService.findOrderCountByDate(date);
                visitsCountList = orderService.findVisitsCountByDate(date);
            } else {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String[] vl = value.split(",");
                Date parse = sdf.parse(vl[1]);
                calendar = Calendar.getInstance();
                calendar.setTime(parse);
                calendar.add(Calendar.DATE, -7);
                date = new ArrayList();
                for (int i = 0; i < 7; i++) {
                    calendar.add(Calendar.DATE, 1);
                    date.add(sdf.format(calendar.getTime()));
                }
                orderCountList = orderService.findOrderCountByDate(date);
                visitsCountList = orderService.findVisitsCountByDate(date);
            }
            map.put("orderDateList", date);// date
            map.put("orderCountList", orderCountList);//预约
            map.put("visitsCountList", visitsCountList);//到诊
            return new Result(true, MessageConstant.GET_ORDERSETTING_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_ORDERSETTING_FAIL);
        }
    }


    /**
     * 体检收入统计
     */
    @PostMapping("/setmealincome")
    public Result getSetmealIncome(String value) {
        try {
            Map map = new HashMap();
            List<Map<String, Object>> setmealPrice = null; // ServiceReturn
            List<String>  setmealNames = null; // names
            Map<String,Object> map1 = null;
            if (value == null || value == "") {
                setmealNames = new ArrayList<>();
                Integer countPrice = setmealService.findSetmealPriceByCount();
                map1 = new HashMap<>();
                map1.put("name","总收入");
                map1.put("value",countPrice);
                setmealPrice = setmealService.findAllOrderSetmealByPrice();
                setmealPrice.add(map1);
                for (Map<String, Object> list : setmealPrice) {
                    String name = (String) list.get("name");
                    setmealNames.add(name);
                }
            } else {
                setmealNames = new ArrayList<>();
                String[] vl = value.split(",");
                String startTime = vl[0];
                String endTime = vl[1];
                Integer countPrice = setmealService.findSetmealPriceByDateAndCount(startTime,endTime);
                map1 = new HashMap<>();
                map1.put("name","总收入");
                map1.put("value",countPrice);
                setmealPrice = setmealService.findSetmealPriceByDate(startTime,endTime);
                setmealPrice.add(map1);
                for (Map<String, Object> list : setmealPrice) {
                    String name = (String) list.get("name");
                    setmealNames.add(name);
                }
            }
            map.put("setmealNames", setmealNames);
            map.put("setmealPrice", setmealPrice);
            return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }


    /**
     * 会员年龄分布数量
     * @return
     */
    @PostMapping("/member/age")
    public Result getMemberAgeCorrespondingName(){
        try {
           List<Integer> memberCount =  memberService.findMemberCountByAge();
            return new Result(true,MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,memberCount);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }

}
